#!/usr/bin/env python
#!-*- coding:utf-8 -*-
import cgi
import os
import datetime
import string
import re, urllib

from time import strftime, localtime

from google.appengine.api import users    #using of google account 
from google.appengine.ext import webapp
from google.appengine.ext import db       #using of data storage
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import template
from db.OrderData import OrderData
from db.tempFile import tempFile
from google.appengine.ext.webapp import blobstore_handlers
from webapp.FileBlob import Storage

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):

    def post(self):

        #order_number = self.request.get('form_order_number')
        #complete_contact_dept = self.request.get('complete_contact_dept')
        # Blobstore にアップロードされたファイルの情報を取得
        files = self.get_uploads('file')
        blob_info = files[0]

        # ファイル表示用の URL へリダイレクト
        #self.redirect('/serve/%s' % blob_info.key())
        #self.redirect('./create_new_detail？order_number=20120130001&blobKey=%s' % blob_info.key())
        #url = './create_new_detail?order_number=%s&blobKey=%s&complete_contact_dept=%s' % (order_number, blob_info.key(), complete_contact_dept)
        #self.redirect(url)
        #self.redirect(url)

       
class DetailPage(webapp.RequestHandler):
    def get(self):

        #view
        current_order_number = self.request.get("order_number","create_new")

        #添付ファイルを貼り付け
        current_file_key = self.request.get("blobKey","none")

        upload_url = blobstore.create_upload_url('/upload')

        # Blobstore に保存されているファイルを取得
        filename = blobstore.BlobInfo.get(current_file_key)
        filenameKey1 = current_file_key
        files = []
        if current_order_number == "create_new" : 
            #create new
            view_data = OrderData()
            #number,author,date
            view_data.order_number  = current_order_number
            view_data.order_author  = users.get_current_user()
            view_data.order_date    = datetime.datetime.today() + datetime.timedelta(hours=9)
        else:
            #modify
            view_datas = db.GqlQuery("select * from OrderData where order_number = :1",
                                    current_order_number)
        
            if view_datas.count() > 0:
                view_data = view_datas[0]
                        
                # Blobstore に保存されているファイルを取得
                view_tempFile = tempFile()
                view_tempFiles = db.GqlQuery("select * from tempFile where order_number = :1",
                                        current_order_number)
                if view_tempFiles.count() > 0:
                    filename = ""
                    blob_key = ""
                    for fileData in view_tempFiles:
                        blob_key = (fileData.tempfile_key).decode('utf-8')
                        files1 = blobstore.BlobInfo.get(blob_key)
                        filename = fileData.tempfile_name
                        dic = {'foo':str(blob_key), 'bar':filename}
                        s = FileBlob.Storage(dic)
                        files.append(s)
        if view_data:
            view_data_front = {
               'order_number':view_data.order_number if view_data.order_number else "",

                'order_author':view_data.order_author if view_data.order_author else "",
                'order_dept':view_data.order_dept if view_data.order_dept else "",
                'order_author_title':view_data.order_author_title if view_data.order_author_title else "",
                'order_date':view_data.order_date if view_data.order_date else "",

                'estimate_contact_author':view_data.estimate_contact_author if view_data.estimate_contact_author else "",
                'estimate_contact_dept':view_data.estimate_contact_dept if view_data.estimate_contact_dept else "",
                'estimate_contact_author_title':view_data.estimate_contact_author_title if view_data.estimate_contact_author_title else "",
                'estimate_contact_date':view_data.estimate_contact_date if view_data.estimate_contact_date else "",

                'operation_author':view_data.operation_author if view_data.operation_author else "",
                'operation_dept':view_data.operation_dept if view_data.operation_dept else "",
                'operation_author_title':view_data.operation_author_title if view_data.operation_author_title else "",
                'operation_date':view_data.operation_date if view_data.operation_date else "",

                'confirm_author':view_data.confirm_author if view_data.confirm_author else "",
                'confirm_dept':view_data.confirm_dept if view_data.confirm_dept else "",
                'confirm_author_title':view_data.confirm_author_title if view_data.confirm_author_title else "",
                'confirm_date':view_data.confirm_date if view_data.confirm_date else "",

                'complete_contact_author':view_data.complete_contact_author if view_data.complete_contact_author else "",
#                'complete_contact_dept':view_data.complete_contact_dept if not None else "",
                'complete_contact_dept': view_data.complete_contact_dept if view_data.complete_contact_dept else "",
                'complete_contact_author_title':view_data.complete_contact_author_title if view_data.complete_contact_author_title else "",
                'complete_contact_date':view_data.complete_contact_date if view_data.complete_contact_date else "",

                'confirm_status':view_data.confirm_status if view_data.confirm_status else "",
                'confirm_message':view_data.confirm_message if view_data.confirm_message else "",

                'company_code':view_data.company_code if view_data.company_code else "",
                'company_name':view_data.company_name if view_data.company_name else "",
                'company_type':view_data.company_type if view_data.company_type else "",
                'company_service':view_data.company_service if view_data.company_service else "",

                'order_type':view_data.order_type if view_data.order_type else "",
                'order_content':view_data.order_content if view_data.order_content else "",
                'order_effect':view_data.order_effect if view_data.order_effect else "",

                'demand_release_date':view_data.demand_release_date if view_data.demand_release_date else "",
                'demand_service_date':view_data.demand_service_date if view_data.demand_service_date else "",

                'estimate_author':view_data.estimate_author if view_data.estimate_author else "",
                'estimate_develop':view_data.estimate_develop if view_data.estimate_develop else "",
                'estimate_cost':view_data.estimate_cost if view_data.estimate_cost else "",
                'estimate_release':view_data.estimate_release if view_data.estimate_release else "",
                'estimate_message':view_data.estimate_message if view_data.estimate_message else "",

                'complete_frontse':view_data.complete_frontse if view_data.complete_frontse else "",
                'complete_se':view_data.complete_se if view_data.complete_se else "",
                'complete_pg':view_data.complete_pg if view_data.complete_pg else "",
                'complete_status':view_data.complete_status if view_data.complete_status else "",

                'complete_service_date':view_data.complete_service_date if view_data.complete_service_date else "",
                'complete_message':view_data.complete_message if view_data.complete_message else "",
                
                'business_conditions':view_data.business_conditions if view_data.business_conditions else None,
                'stocktaking_methods':view_data.stocktaking_methods if view_data.stocktaking_methods else None,
                'classification':view_data.classification if view_data.classification else "0",
                'need_program':view_data.need_program if view_data.need_program else "0",
                
                'content':view_data.content if view_data.content else "",
                'effective':view_data.effective if view_data.effective else "",
                
                'attched_file_name':view_data.attched_file_name if view_data.attched_file_name else "",
                'attched_file':view_data.attched_file,

                'filename':filename,
                'filenameKey1':filenameKey1,
                'files':files
            }
        path = os.path.join(os.path.dirname(__file__),'../html/order_detail.html')
        self.response.out.write(template.render((path),view_data_front))

    def post(self):        
        #generate order_number by date
        if self.request.get('form_order_number_1') == "create_new" :
            post_data = OrderData()
            
            #order number
            date_today = strftime("%Y",localtime()) + strftime("%m",localtime()) + strftime("%d",localtime())

            temp_data = db.GqlQuery("select * from OrderData where order_number > :1 order by order_number DESC",
                                    date_today)
            temp_count = temp_data.count()
            
            if temp_count > 0:
                mydata = temp_data.get()
                temp_number = string.atoi(mydata.order_number) + 1
                post_data.order_number = str(temp_number)
            else:
                #first data of today
                post_data.order_number = date_today + "001"
            
            #author
            post_data.order_author    =    users.get_current_user()
                
        else:
            post_datas = db.GqlQuery("select * from OrderData where order_number = :1",
                                    self.request.get('form_order_number'))
            if post_datas.count() > 0:
                post_data = post_datas[0]
        #post_data.order_number    =    self.request.get('form_order_number')
        #post_data.order_author    =    self.request.get('form_order_author')
        
        if post_data:
            post_data.order_dept    =    self.request.get('form_order_dept')
            post_data.order_author_title    =    self.request.get('form_order_author_title')
            post_data.order_date = datetime.datetime.strptime(self.request.get('form_order_date'), '%Y-%m-%d %H:%M:%S')
#            post_data.order_date    =    datetime(2012, 1, 1, 12, 30, 0)
#            post_data.order_date    =    self.request.get('form_order_date')
#            post_data.order_date    =    "2012/01/01T12:30:00"
#            2012-01-23 20:53:26.798000
    
            post_data.estimate_contact_author    =    self.request.get('form_estimate_contact_author')
            post_data.estimate_contact_dept    =    self.request.get('form_estimate_contact_dept')
            post_data.estimate_contact_author_title    =    self.request.get('form_estimate_contact_author_title')
            post_data.estimate_contact_date    =    None if self.request.get('form_estimate_contact_date') == "" else datetime.datetime.strptime(self.request.get('form_estimate_contact_date'), '%Y-%m-%d %H:%M:%S')
    
            post_data.operation_author    =    self.request.get('form_operation_author')
            post_data.operation_dept    =    self.request.get('form_operation_dept')
            post_data.operation_author_title    =    self.request.get('form_operation_author_title')
    #        post_data.operation_date    =    self.request.get('form_operation_date')
    
            post_data.confirm_author    =    self.request.get('form_confirm_author')
            post_data.confirm_dept    =    self.request.get('form_confirm_dept')
            post_data.confirm_author_title    =    self.request.get('form_confirm_author_title')
    #        post_data.confirm_date    =    self.request.get('form_confirm_date')
    
            post_data.complete_contact_author    =    self.request.get('form_complete_contact_author')
            post_data.complete_contact_dept    =    self.request.get('form_complete_contact_dept')
            post_data.complete_contact_author_title    =    self.request.get('form_complete_contact_author_title')
    #        post_data.complete_contact_date    =    self.request.get('form_complete_contact_date')
    
            post_data.confirm_status    =    self.request.get('form_confirm_status')
            post_data.confirm_message    =    self.request.get('form_confirm_message')
    
            post_data.company_code    =    self.request.get('form_company_code')
            post_data.company_name    =    self.request.get('form_company_name')
            post_data.company_type    =    self.request.get('form_company_type')
            post_data.company_service    =    self.request.get('form_company_service')
    
            post_data.order_type    =    self.request.get('form_order_type')
            post_data.order_content    =    self.request.get('form_order_content')
            post_data.order_effect    =    self.request.get('form_order_effect')
    
    #        post_data.demand_release_date    =    self.request.get('form_demand_release_date')
    #        post_data.demand_service_date    =    self.request.get('form_demand_service_date')
    
            post_data.estimate_author    =    self.request.get('form_estimate_author')
    #        post_data.estimate_develop    =    self.request.get('form_estimate_develop')
    #        post_data.estimate_cost    =    self.request.get('form_estimate_cost')
    #        post_data.estimate_release    =    self.request.get('form_estimate_release')
    #        post_data.estimate_message    =    self.request.get('form_estimate_message')
    
    #        post_data.complete_frontse    =    self.request.get('form_complete_frontse')
    #        post_data.complete_se    =    self.request.get('form_complete_se')
    #        post_data.complete_pg    =    self.request.get('form_complete_pg')
    #        post_data.complete_status    =    self.request.get('form_complete_status')
    
    #        post_data.complete_service_date    =    self.request.get('form_complete_service_date')
    #        post_data.complete_message    =    self.request.get('form_complete_message')
    
#            upload_files = self.get_uploads('file')  # 'file' is file upload field in the form 
#            for blob_info in upload_files:
#                blob_info.key()
            post_data.attched_file_name =   self.request.get('filename')
            post_data.attched_file      =   db.Blob(self.request.get('file')) if self.request.get('file') else None
            
#            post_data.attched_file      =   db.Blob(self.request.get('file'))

            post_data.business_conditions = self.request.get_all('business_conditions')
            post_data.stocktaking_methods = self.request.get_all('stocktaking_methods')
            post_data.classification = self.request.get('classification')
            post_data.need_program = self.request.get('need_program')

            post_data.content = self.request.get('content')
            post_data.effective = self.request.get('effective')
            
            post_data.put()
            
#            self.redirect(blobstore.create_upload_url('/'), self.request.get('file'))
            

#            userInfo = users.get_current_user()
#            if userInfo:
##                mail.send_mail(sender="Xin Zhang <xin.zhang@ajis-group.com>", 
##                              to="""Mieko Suzuki <mieko.suzuki@ajis-group.com>, 
##                              Kexin Yuan <kexin.yuan@ajis-group.com>,
##                              Xin Zhang.wind <zhangxin_wind@yahoo.co.jp>,""", 
#                mail.send_mail(sender=userInfo.email(),
#                              to=userInfo.email(),
#                              subject="Welcome to access my Page",
#                              body="")
#                self.response.out.write("Send mail.")
#            else:
#                self.response.out.write("Please Login Gmail.")
                        
            self.redirect('/')